﻿using System;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;

namespace JumpingBalls.AppCode
{
    public static class Tops
    {
        private const int topCount = 20;

        private const string topsKey = "topsKey";

        public static readonly ObservableCollection<TopItem> TopsList;

        static Tops()
        {
            // if not exist, create an empty tops
            if(!IsolatedStorageSettings.ApplicationSettings.Contains(topsKey))
            {
                TopsList = new ObservableCollection<TopItem>();

                for (int i = 0; i < topCount; i++)
                {
                    TopsList.Add(new TopItem{Rank = i+1, Score = int.MinValue, CreateDate = DateTime.MaxValue});
                }

                IsolatedStorageSettings.ApplicationSettings[topsKey] = TopsList;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }

            // get tops from IsolatedStorageSettings
            TopsList = IsolatedStorageSettings.ApplicationSettings[topsKey] as ObservableCollection<TopItem>;
        }

        public static void AddToTop(TopItem topItem)
        {
            for (int i = 0; i < TopsList.Count; i++)
            {
                if (topItem.Score > TopsList[i].Score)
                {
                    for (int j = TopsList.Count - 1; j > i; j--)
                    {
                        TopsList[j] = TopsList[j - 1];
                        TopsList[j].Rank++;
                    }

                    topItem.Rank = i + 1;

                    TopsList[i] = topItem;

                    break;
                }
            }

            IsolatedStorageSettings.ApplicationSettings[topsKey] = TopsList;
            IsolatedStorageSettings.ApplicationSettings.Save();
        }
    }

    public class TopItem
    {
        public int Rank { get; set; }

        public int Score { get; set; }

        public DateTime CreateDate { get; set; }
    }

    //public class TopItemSort : IComparer<TopItem>
    //{
    //    public int Compare(TopItem x, TopItem y)
    //    {
    //        if (x.Score > y.Score) return 1;
    //        if ((x.Score == y.Score) && (x.CreateDate > y.CreateDate)) return 1;
    //        if ((x.Score == y.Score) && (x.CreateDate < y.CreateDate)) return -1;
    //        if (x.Score < y.Score) return -1;

    //        return 0;
    //    }
    //}  
}
